package com.example.netty.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zclever <304078606@qq.com>
 * @date 2021-03-02
 */
@Component
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private CommonHandler commonHandler;

    @Autowired
    private GameHandler gameHandler;

    @Autowired
    private MatchHandler matchHandler;

    @Autowired
    private RoomHandler roomHandler;

    @Autowired
    private FightHandler fightHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        ChannelPipeline pipeline= socketChannel.pipeline();

        //以下三个是Http的支持
        //http解码器
        pipeline.addLast(new HttpServerCodec());
        //支持写大数据流
        pipeline.addLast(new ChunkedWriteHandler());
        //http聚合器
        pipeline.addLast(new HttpObjectAggregator(65536));
        //websocket支持,设置路由
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        //添加自定义的助手类,这里不能使用new，不然在handler中不能注入依赖
        pipeline.addLast(commonHandler);
        pipeline.addLast(gameHandler);
        pipeline.addLast(matchHandler);
        pipeline.addLast(roomHandler);
        pipeline.addLast(fightHandler);
//        pipeline.addLast(new IdleStateHandler(60,60,60));
//        pipeline.addLast(new PingHandler());
    }
}
